import 'package:enjoy_plus_bryant/pages/home/index.dart';
import 'package:enjoy_plus_bryant/pages/mine/index.dart';
import 'package:enjoy_plus_bryant/utils/eventbus.dart';
import 'package:enjoy_plus_bryant/utils/token.dart';
import 'package:flutter/material.dart';

class TabBarPage extends StatefulWidget {
  const TabBarPage({super.key});

  @override
  State<TabBarPage> createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> {
  // 当前TabBar索引
  int currentIndex = 0;
  // 底部TabBar数据
  List tabBarList = [
    {
      "title": "首页",
      "default": "assets/tabs/home_default.png",
      "active": "assets/tabs/home_active.png",
    },
    {
      "title": "我的",
      "default": "assets/tabs/my_default.png",
      "active": "assets/tabs/my_active.png",
    },
  ];

  // 创建底部TabBarItem
  List<BottomNavigationBarItem> barItemList() {
    List<BottomNavigationBarItem> items = [];
    for (var item in tabBarList) {
      items.add(
        BottomNavigationBarItem(
          icon: Image.asset(item["default"], width: 32, height: 30),
          activeIcon: Image.asset(item["active"], width: 32, height: 32),
          label: item["title"],
        ),
      );
    }
    return items;
  }

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () async {
      await TokenManager().init();
      // print(TokenManager().getToken());
      // ToastUtil.showSuccess(TokenManager().getToken() ?? "未登录");
    });

    eventBus.on<LogoutEvent>().listen((event) {
      // 跳转登录页面
      Navigator.pushNamed(context, '/login');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:
          // 安全区
          SafeArea(
            top: false,
            bottom: false,
            child: IndexedStack(
              // 索引切换
              index: currentIndex,
              children: [
                HomePage(),
                MinePage(currentIndex: currentIndex),
              ],
            ),
          ),

      bottomNavigationBar: BottomNavigationBar(
        currentIndex: currentIndex,
        items: barItemList(),
        selectedItemColor: const Color.fromARGB(255, 85, 145, 175),
        unselectedItemColor: Colors.black,
        onTap: (value) {
          setState(() {
            currentIndex = value;
          });
        },
      ),
    );
  }
}
